// pages/sys/login/login.js
const config = require('./config');
var Zan = require('../../../dist/index');
var app = getApp();
var requestUrl = app.globalData.requestUrl;
const md5 = require('../../../utils/md5.js');
const Util = require('../../../utils/util.js');
Page(Object.assign({}, Zan.Field, Zan.TopTips, {

  /**
   * 页面的初始数据
   */
  data: {
		config,
		username: '',
		sms: '',
		password: '111111',
		autoLogin: true,
		loading: false,
		btnName: "登录",
		verBtnName: '获取验证码',
		btnClass: 'zan-btn zan-btn--small zan-btn--primary',
		verDisabled: false,
		time: 60,
		failNum: 0,
		logout: ''
  },
	// 输入框内容更改时触发
	handleZanFieldChange({ componentId, detail }) {
		if (componentId == 'username') {
			this.setData({
				username: detail.value
			})
		}
	},
	getVerCode: function () {
		var that = this;
		var account = this.data.username.trim();
		if (Util.isNull(account)) {
			this.showZanTopTips("手机号不能为空!");
			return false;
		}
		if (!Util.isTel(account)) {
			this.showZanTopTips("请输入正确的手机号");
			return false;
		}
		this.setData({
			verDisabled: true,
			btnClass: 'zan-btn zan-btn--small zan-btn--default'
		});
		var time = this.data.time;
		var index = setInterval(function () {
			time--;
			if (time >= 0) {
				var verBtnName = time + "s 可重新获取";
				that.setData({
					verBtnName: verBtnName
				});
			} else {
				clearInterval(index);
				that.setData({
					verDisabled: false,
					verBtnName: "重新获取",
					btnClass: 'zan-btn zan-btn--small zan-btn--primary'
				});
			}
		}, 1000);
		// 发送请求
		wx.request({
			url: requestUrl + "register/sendSMS",
			method: 'GET',
			dataType: 'json',
			data: {
				username: account
			},
			header: {
				'content-type': 'application/json'
			},
			success: function (res) {
				var data = res.data;
				console.log("请求成功" + JSON.stringify(data));
				if (data.success == "true") {
					wx.showToast({
						title: "发送成功请注意查收"
					})
				} else {
					wx.showToast({
						title: "发送失败"
					})
					clearInterval(index);
					that.setData({
						verDisabled: false,
						verBtnName: "重新获取",
						btnClass: 'zan-btn zan-btn--small zan-btn--primary'
					});
				}

			},
			fail: function () {
				wx.showToast({
					title: "发送失败"
				})
				clearInterval(index);
				that.setData({
					verDisabled: false,
					verBtnName: "重新获取",
					btnClass: 'zan-btn zan-btn--small zan-btn--primary'
				});
			}
		})
	},
	verInput: function (e) {
		var sms = e.detail.value;
		console.log("验证码: " + sms);
		this.setData({
			sms: sms
		});
	},
	login: function () {
		var that = this;
		var sms = this.data.sms;
		var username = this.data.username;
		console.log("sms: " + sms + ", username: " + username);
		var url = requestUrl + 'mui/login';
		var autoLogin = this.data.autoLogin;
		console.log("autoLogin: "+autoLogin)
		var data = {}
		if (!autoLogin) { // 需要输入手机号验证码
			if (Util.isNull(username)) {
				this.showZanTopTips("手机号不能为空");
				return false;
			}
			if (Util.isNull(sms)) {
				this.showZanTopTips("验证码不能为空");
				return false;
			}
			// if (!Util.isTel(username)) {
			// 	this.showZanTopTips("手机号格式不正确");
			// 	return false;
			// }
			url = requestUrl + 'register/userRegister';
			data.username = username;
			data.sms = sms;
			this.setData({
				loading: true,
				btnName: "正在登录"
			});
			
		}
		wx.showLoading({
			title: '登录中...',
			mask: true
		})
		console.log("url: " + url)
		wx.login({
			success: function (res) {
				var code = res.code;
				if (res.code) {
					data.code = res.code;
					console.log("请求参数data: " + JSON.stringify(data) )
					//发起网络请求
					wx.request({
						url: url,
						method: 'GET',
						dataType: 'json',
						data: data,
						success: function (res) {
							var data = res.data;
							console.log("登录请求返回: " + JSON.stringify(data));
							console.log("message: "+ data.message)
							wx.hideLoading()
							if (data.result == "true") { // 登录成功
								var phone = data.data.phone;
								var sibrccode = data.data.sibrccode;
								var name = data.data.name;
								var checkflag = data.data.checkflag; // 1为可以审核
								var userid = data.data.userid;
								console.log("userid: " + userid)

								var oldPhone = wx.getStorageSync('phone');
								console.log("oldPhone:" + oldPhone)
								if (oldPhone && oldPhone != phone) {
									console.log("清除缓存")
									// wx.removeStorageSync('sysMsg')
									// wx.removeStorageSync('newDate')
									// wx.removeStorageSync('newTime')
									wx.clearStorageSync()
								}

								// wx.setStorageSync('autoLogin', true); // 登录成功修改为true, 下次默认自动登录

								wx.setStorageSync('phone', phone);
								wx.setStorageSync('sibrccode', sibrccode);
								wx.setStorageSync('name', name);
								wx.setStorageSync('userid', userid); // 用户id
								wx.setStorageSync('checkflag', checkflag); // 用户权限
								wx.reLaunch({
									url: '/pages/message/index/index'
								})
								
							} else {
								that.setData({
									autoLogin: false
								})
								// wx.setStorageSync('autoLogin', false);
								setTimeout(() => {
									that.showZanTopTips(data.message);
								}, 300)
							}
							that.setData({
								loading: false,
								btnName: "登录"
							});
							
						},
						fail: function (e) {
							wx.hideLoading()
							console.log(e)
							that.setData({
								autoLogin: false,
								loading: false,
								btnName: "登录"
							})
							// wx.setStorageSync('autoLogin', false);
							setTimeout(() => {
								that.showZanTopTips("登录失败! ");
							}, 300)
						}
					})
				} else {
					that.setData({
						autoLogin: false,
						loading: false,
						btnName: "登录"
					})
					// wx.setStorageSync('autoLogin', false);
					setTimeout(() => {
						that.showZanTopTips("获取用户登录态失败！ ");
					}, 300)
					wx.hideLoading()
				}
			},
			fail: function () {
				that.setData({
					autoLogin: false,
					loading: false,
					btnName: "登录"
				})
				// wx.setStorageSync('autoLogin', false);
				setTimeout(() => {
					that.showZanTopTips("获取用户登录态失败！");
				}, 300)
				wx.hideLoading()
			}
		})
	},
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
		var that = this;
		try {
			app.getUserInfo(function (userInfo) {
				console.log(userInfo)
				// 头像
				var imgSrc = userInfo.avatarUrl;
				console.log(imgSrc)
				wx.setStorageSync('imgSrc', imgSrc)
			})
			var phone = wx.getStorageSync('phone');
			console.log("phone: " + phone)
			if (phone != "") {
				this.setData({
					'config.username.value': phone,
					username: phone
				});
			}
		} catch (e) {

		}
		
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
		this.login();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  }
}))